package cn.cms.taglib;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;

/**
 * Created by leon on 2017/2/20.
 */
public class GetJsonTag extends TagSupport {

    public String jsonArray;

    public String outKey;

    public String getJsonArray() {
        return jsonArray;
    }

    public void setJsonArray(String jsonArray) {
        this.jsonArray = jsonArray;
    }

    public String getOutKey() {
        return outKey;
    }

    public void setOutKey(String outKey) {
        this.outKey = outKey;
    }

    @Override
    public int doStartTag() throws JspException {

        JspWriter jspWriter = this.pageContext.getOut();

//        if (StringUtils.isBlank(jsonArray) || "[]".equals(jsonArray) || "[  ]".equals(jsonArray)) {
//
//            try {
//
//                jspWriter.print("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1487588530417&di=276042ab2927a338090afbd4451e24f8&imgtype=0&src=http%3A%2F%2Fi.noniu.com%2F2015%2F0430%2F20150430103740939.jpg");
//                return super.doStartTag();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }

        try {
            if (StringUtils.isNotBlank(jsonArray)) {
                JSONArray json = JSON.parseArray(jsonArray);
                if (json.size() > 0) {

                    JSONObject jsonObject = json.getJSONObject(0);
                    jspWriter.print(jsonObject.get(outKey));
                } else {

                    jspWriter.print("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1487588530417&di=276042ab2927a338090afbd4451e24f8&imgtype=0&src=http%3A%2F%2Fi.noniu.com%2F2015%2F0430%2F20150430103740939.jpg");
                }
            } else {
                jspWriter.print("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1487588530417&di=276042ab2927a338090afbd4451e24f8&imgtype=0&src=http%3A%2F%2Fi.noniu.com%2F2015%2F0430%2F20150430103740939.jpg");
            }
        } catch (Exception e) {
            try {
                jspWriter.print("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1487588530417&di=276042ab2927a338090afbd4451e24f8&imgtype=0&src=http%3A%2F%2Fi.noniu.com%2F2015%2F0430%2F20150430103740939.jpg");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return super.doStartTag();
    }
}
